package com.pospi.xstore.ui.cash_ui;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pospi.xstore.App;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.PointSelectLeftAdapter;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.dto.MenuDto;
import com.pospi.xstore.dto.OrderDto;
import com.pospi.xstore.dto.TableStatusConstance;
import com.pospi.xstore.dto.Tablebeen;
import com.pospi.xstore.greendao.TablebeenDao;
import com.pospi.xstore.http.MaxNO;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.caigou.CgDetailActivity;
import com.pospi.xstore.util.DoubleSave;
import com.pospi.xstore.util.SaveMenuInfo;
import com.pospi.xstore.util.SaveOrderInfo;
import com.pospi.xstore.util.TurnSize;
import com.pospi.xstore.view.PointSelectUtil.PinnedHeaderListView;
import com.pospi.xstore.view.PointSelectUtil.TestSectionedAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PointGoodsActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.parent)
    LinearLayout parent;
    @Bind(R.id.order_detail)
    ImageView orderDetail;
//    @Bind(R.id.what_money)
//    TextView tvMoney;
    @Bind(R.id.settle)
    TextView settle;
    @Bind(R.id.ll_bottom)
    LinearLayout llBottom;
    @Bind(R.id.left_listview)
    ListView left_listView;
    @Bind(R.id.pinnedListView)
    PinnedHeaderListView right_listview;
    @Bind(R.id.retain)
    TextView retain;
    @Bind(R.id.cart_anim_icon)
    ImageView mAnimImageView;
    @Bind(R.id.iv_search_xz)
    ImageView iv_search_xz;
    @Bind(R.id.et_code_counts)
    EditText et_code_counts;


    private TablebeenDao tablebeenDao;

    private Animation mAnimation;
    private TestSectionedAdapter sectionedAdapter;
    private List<GoodsDto> goodinfos = new ArrayList<>();
    private List<List<GoodsDto>> lists;
    private PointSelectGoodsDetailAdapter adapter;
    private double totalMoney = 0;
    private int scrollNum;

    private String maxNO;
    private OrderDto orderDto;
    private GoodsDto goodsDto;
    private PopupWindow mPricePopupWindow;
    private EditText good_weight;
    private Tablebeen tablebeenen;
    private DecimalFormat decimalFormat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_point_goods);
        decimalFormat = new DecimalFormat("###################.###########");
        setTitle("选择商品");
        ButterKnife.bind(this);
        tablebeenDao = App.getInstance().getDaoSession().getTablebeenDao();
        tablebeenen = (Tablebeen) getIntent().getSerializableExtra("table");
        addData();

    }


    public void init() {
        orderDto = (OrderDto) getIntent().getSerializableExtra(RestOrderActivity.REST_ORDER);
        if (orderDto != null) {
            maxNO = orderDto.getMaxNo();
            if (orderDto.getmTableId() != null) {
                tablebeenen = tablebeenDao.queryBuilder().where(TablebeenDao.Properties.TId.eq(orderDto.getmTableId())).unique();
                updateTableRest(orderDto.getmTableId());
            }

            Log.i("跳转之后", "NO" + orderDto.getMaxNo() + "");
            goodinfos = SaveOrderInfo.changeToList(orderDto.getOrder_info());

        } else {
            maxNO = MaxNO.getMaxNo(getApplicationContext());
            goodinfos = new ArrayList<>();
        }

        totalMoney = 0;
        for (int i = 0; i < goodinfos.size(); i++) {
            totalMoney += goodinfos.get(i).getPrice() * goodinfos.get(i).getNum();
        }
//        tvMoney.setText(decimalFormat.format(DoubleSave.doubleSaveTwo(totalMoney)));

    }

    public void addData() {
        lists = new ArrayList<>();
        String menuInfo = getSharedPreferences("MenuDto_json", MODE_PRIVATE).getString("json", "");
        List<MenuDto> menuDtos = SaveMenuInfo.changeToList(menuInfo);
        List<String> titles = new ArrayList<>();
        List<String> code = new ArrayList<>();
        for (int i = 0; i < menuDtos.size(); i++) {
            titles.add(menuDtos.get(i).getName());
            code.add(menuDtos.get(i).getSid());
        }
        GoodsDao dao = new GoodsDao(getApplicationContext());
        for (int i = 0; i < titles.size(); i++) {
            Log.i("code", code.get(i)+"==============");
            List<GoodsDto> goodsBeens = dao.findSelectPointGoods(code.get(i));
            lists.add(goodsBeens);
        }

        sectionedAdapter = new TestSectionedAdapter(this, titles, lists);
        right_listview.setAdapter(sectionedAdapter);

        PointSelectLeftAdapter leftAdapter = new PointSelectLeftAdapter(getApplicationContext(), titles);
        left_listView.setAdapter(leftAdapter);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onStart() {
        super.onStart();
        init();
        mAnimation = AnimationUtils.loadAnimation(PointGoodsActivity.this, R.anim.cart_anim);
        mAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mAnimImageView.setVisibility(View.INVISIBLE);
            }
        });
        left_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position,
                                    long arg3) {
                int rightSection = 0;
                for (int i = 0; i < position; i++) {
                    rightSection += sectionedAdapter.getCountForSection(i) + 1;
                }
                right_listview.setSelection(rightSection);
            }
        });

        left_listView.setOnScrollListener(new ListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                scrollNum = firstVisibleItem;
            }
        });


        //选择商品
        right_listview.setOnItemClickListener(new PinnedHeaderListView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int section, int position, long id) {

                goodsDto = lists.get(section).get(position);
//                if (!goodsDto.getGroup_sid().equals("null")) {
//                    String[] groupsids = goodsDto.getGroup_sid().split(",");
//                    Intent intent = new Intent(PointSelectActivity.this, ModifiedDialogActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putStringArray("groupsids", groupsids);
//                    bundle.putSerializable("goods", goodsDto);
//                    bundle.putString("good_name", goodsDto.getName());
//                    intent.putExtras(bundle);
//                    startActivityForResult(intent, ModifiedDialogActivity.REQUESTCODE);
//                    return;
//                } else {
//                    if (goodsDto.getUnit().equals("2")) {//称重商品
//                        showSetWeightPopupWindow();
//                    } else {
//                        addGoods(goodsDto);
//                    }
//                }

//                addGoods(goodsDto);

                showSetWeightPopupWindow();
            }


            @Override
            public void onSectionClick(AdapterView<?> adapterView, View view, int section, long id) {
            }
        });

        right_listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                int onScrollItem = sectionedAdapter.getSectionForPosition(firstVisibleItem);
                for (int i = 0; i < left_listView.getChildCount() + scrollNum; i++) {
                    if (i == onScrollItem) {
                        if (i - scrollNum > -1) {
                            left_listView.getChildAt(i - scrollNum)
                                    .setBackgroundColor(getResources().getColor(R.color.white));
                            left_listView.setSelection(onScrollItem);
                        }
                    } else {
                        try {
                            left_listView.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.colorBackground));
                        } catch (Exception e) {
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //换桌
        tablebeenen = (Tablebeen) intent.getSerializableExtra("table");
    }

    //添加商品
    private void addGoods(GoodsDto goodsDto) {
        Log.i("Modified", goodsDto.getModified() + goodsDto.getName() + goodsDto.getPrice());
        showAnimation();
        if (!checkGoods(goodsDto)) {
            goodinfos.add(goodsDto);
        }
    }

    private boolean checkGoods(GoodsDto goodsDto) {
        for (GoodsDto dto : goodinfos) {
            if (dto.getSid().equals(goodsDto.getSid())) {
                dto.setNum(DoubleSave.doubleSaveTwo(dto.getNum() + goodsDto.getNum()));
                return true;
            }
        }
        return false;
    }

    public void showAnimation() {
        mAnimImageView.startAnimation(mAnimation);
        mAnimImageView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ModifiedDialogActivity.REQUESTCODE:
                switch (resultCode) {
                    case ModifiedDialogActivity.RESULTCODE_CANCLE:
                        break;
                    case ModifiedDialogActivity.RESULTCODE_SURE:
                        Bundle bundle = data.getExtras(); //data为B中回传的Intent
                        Set<String> set = (Set<String>) bundle.getSerializable("modifieds");
                        GoodsDto dto = (GoodsDto) bundle.getSerializable("goods");
//                        List<ModifiedDto> modifiedDtos = (List<ModifiedDto>) bundle.getSerializable("modifieds");

                        String remark = "";
                        for (String s : set) {
                            remark += (s + " ");
                        }
                        addGoods(dto);

                        break;
                }
                break;
        }
    }

    @OnClick({R.id.order_detail, R.id.settle, R.id.retain})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.order_detail:
            case R.id.retain:
                LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                View contentView = mLayoutInflater.inflate(R.layout.pointselect_detail, null);
                // R.layout.pop为PopupWindow 的布局文件
                PopupWindow pop = new PopupWindow(contentView, ActionBar.LayoutParams.MATCH_PARENT, TurnSize.dip2px(getApplicationContext(), 300));
                pop.setBackgroundDrawable(new BitmapDrawable());
                // 指定 PopupWindow 的背景
                pop.setFocusable(true);
                //指定PopupWindow显示在你指定的view下

                int[] location = new int[2];
                llBottom.getLocationOnScreen(location);
                pop.showAtLocation(llBottom, Gravity.NO_GRAVITY, location[0], location[1] - pop.getHeight());

                ListView info = (ListView) contentView.findViewById(R.id.lv_detail);
                adapter = new PointSelectGoodsDetailAdapter(getApplicationContext(), goodinfos);
                info.setAdapter(adapter);
//                Constant.fixListViewHeight(info);
                RelativeLayout ll = (RelativeLayout) contentView.findViewById(R.id.delete);
                ll.setOnClickListener(this);
                break;
            case R.id.settle:
//                UnionConfig.accessToken();
                if (goodinfos.isEmpty()) {
                    showToast("请添加商品");
                } else {
                    SaveOrderInfo.saveAsJson(getApplicationContext(), goodinfos);
                    Intent intent = new Intent(PointGoodsActivity.this, CgDetailActivity.class);
//                    intent.putExtra(ScanReceiptActivity.PUT_MONEY, Double.parseDouble(tvMoney.getText().toString()));
//                    intent.putExtra(ScanReceiptActivity.PUT_MAXNO, MaxNO.getMaxNo(getApplicationContext()));
                    intent.putExtra("goods", SaveOrderInfo.changeGoodDtoToJson(goodinfos));

                    startActivity(intent);
                    finish();
                }
                break;
            case R.id.delete:
                if (goodinfos.isEmpty()) {
                    showToast("商品为空");
                } else {
                    showDeleteDialog();
                }
                break;
//            case R.id.retain:
//                if (goodinfos.isEmpty()) {
//                    showToast("请添加商品");
//                } else {
//                    final AlertDialog deleteDialog = new AlertDialog.Builder(this)
//                            .setTitle("提示")
//                            .setMessage("确定挂单？")
//                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                    addRestOrderinfo();
//                                }
//                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                }
//                            })
//                            .create();
//                    deleteDialog.show();
//                }
//                break;
        }
    }
//
//    public void addRestOrderinfo() {
//        if (tablebeenen == null) {
//            tablebeenen = new Tablebeen();
//        }
//        String shopId = getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Id", "");
//        OrderDto orderDto = new OrderDto();
//        orderDto.setmTableNumber(tablebeenen.getNumber());
//        orderDto.setmTableId(tablebeenen.getTId());
//
//        orderDto.setOrder_info(SaveOrderInfo.changeGoodDtoToJson(goodinfos));//存储的该订单的商品的信息
//        orderDto.setPayway(null);
//        orderDto.setTime(GetData.getYYMMDDTime());
//        orderDto.setSs_money(0.00);
//        orderDto.setYs_money(DoubleSave.doubleSaveTwo(Double.parseDouble(tvMoney.getText().toString())));
//        orderDto.setZl_money(0.00);
//        orderDto.setCashiername(App.getCashierMsgDto().getName());
//        orderDto.setCashiernumber(App.getCashierMsgDto().getNumber());
//        orderDto.setShop_id(shopId);
//        orderDto.setOrderType(Constant.ORDERTYPE_GD);
//        orderDto.setMaxNo(maxNO);
//        orderDto.setCheckoutTime(GetData.getDataTime());
//        orderDto.setDetailTime(GetData.getHHmmssTimet());
//        orderDto.setHasReturnGoods(Constant.hasReturnGoods_No);
//        orderDto.setOut_trade_no(null);
//        //当挂单的时候该数据用于保存是哪个界面进行的挂单操作
//        orderDto.setPayReturn(RestOrderActivity.REST_Point);
//        orderDto.setIfFinishOrder(Constant.NO);
//        /**
//         * 给数据库里面添加一条记录
//         */
//        new OrderDao(getApplicationContext()).addOrder(orderDto);
//        goodinfos.clear();
////        adapter.notifyDataSetChanged();
////        tvMoney.setText("0");
//        showToast("挂单成功");
//        updateTableMsg(tablebeenen.getTId());
//
//    }

    public void showDeleteDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("销毁提示")
                .setMessage("确定销毁该订单吗?")
                .setPositiveButton("销毁", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        goodinfos.clear();
//                        tvMoney.setText("0");
                        adapter.notifyDataSetChanged();
                        totalMoney = 0;
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create();
        dialog.show();
    }

    class PointSelectGoodsDetailAdapter extends BaseAdapter {
        private Context context;
        private List<GoodsDto> goodsDtos;

        public PointSelectGoodsDetailAdapter(Context context, List<GoodsDto> goodsDtos) {
            this.context = context;
            this.goodsDtos = goodsDtos;
        }

        @Override
        public int getCount() {
            return goodsDtos.size();
        }

        @Override
        public Object getItem(int position) {
            return goodsDtos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.pointselect_detail_item, null);
                holder = new ViewHolder();
                holder.name = (TextView) convertView.findViewById(R.id.goods_name);
                holder.price = (TextView) convertView.findViewById(R.id.goods_price);
                holder.num = (TextView) convertView.findViewById(R.id.goods_num);
                holder.add = (ImageView) convertView.findViewById(R.id.add_num);
                holder.js = (ImageView) convertView.findViewById(R.id.substract_goods);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            String mo = "";
            if (goodsDtos.get(position).getModified() != null) {
                mo = goodsDtos.get(position).getModified();
            }
            holder.name.setText(goodsDtos.get(position).getName() + "  " + mo);
            holder.num.setText(decimalFormat.format(goodsDtos.get(position).getNum()));

            final double goodsPrice = goodinfos.get(position).getPrice();
            holder.price.setText(decimalFormat.format(goodsPrice));

            holder.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    goodsDtos.get(position).setNum(DoubleSave.doubleSaveTwo(goodsDtos.get(position).getNum() + 1));
                    holder.num.setText(String.valueOf(DoubleSave.doubleSaveTwo(goodsDtos.get(position).getNum())));
                    totalMoney += goodsPrice;
//                    tvMoney.setText(decimalFormat.format(DoubleSave.doubleSaveTwo(totalMoney)));
                }
            });
            holder.js.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (goodsDtos.get(position).getNum() - 1 > 0) {
                        goodsDtos.get(position).setNum(DoubleSave.doubleSaveTwo(goodsDtos.get(position).getNum() - 1));
                        holder.num.setText(String.valueOf(DoubleSave.doubleSaveTwo(goodsDtos.get(position).getNum())));
                    } else {
                        goodsDtos.remove(position);
                        adapter.notifyDataSetChanged();
                    }
                    totalMoney -= goodsPrice;
                    if (totalMoney < 0) {
                        totalMoney = 0;
                    }
//                    tvMoney.setText(decimalFormat.format(DoubleSave.doubleSaveTwo(totalMoney)));
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView name;
            TextView price;
            TextView num;
            ImageView add;
            ImageView js;
        }
    }

    private void showSetWeightPopupWindow() {
        View contentView = LayoutInflater.from(PointGoodsActivity.this).inflate(R.layout.weight_layout, null);
        mPricePopupWindow = new PopupWindow(contentView, getWidth()*2/3, getHeight()*3/5);
        mPricePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPricePopupWindow.setFocusable(true);
        TextView sure = (TextView) contentView.findViewById(R.id.scan_sure);
//        text_num = (TextView) contentView.findViewById(R.id.text_num);
        good_weight = (EditText) contentView.findViewById(R.id.scan_tv_weight);
        TextView clear_weight = (TextView) contentView.findViewById(R.id.clear_weight);
        clear_weight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                numberAdd = "";
                good_weight.setText("");
            }
        });
        mPricePopupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        mPricePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                numberAdd = "";
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String et = good_weight.getText().toString().trim();
                if (isNumber(et)) {
                    goodsDto.setNum(DoubleSave.doubleSaveTwo(Double.parseDouble(et)));
                    addGoods(goodsDto);
                    numberAdd = "";
                    mPricePopupWindow.dismiss();
                } else {
                    Toast.makeText(PointGoodsActivity.this, "请输入正确的数量", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private String numberAdd = "";

    public void popupWindowNumberClick(View view) {
        TextView tv = (TextView) view;
        if (numberAdd.isEmpty()) {
            if (view.getId() != R.id.dian) {
                numberAdd += tv.getText().toString();
            }
        } else {
            if (numberAdd.equals("0") && view.getId() == R.id.dian) {
                numberAdd = tv.getText().toString();
            } else {
                numberAdd += tv.getText().toString();
            }
        }
        good_weight.setText(numberAdd);
    }

    public static boolean isNumber(String str) {
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }
    private void updateTableMsg(String sid){
        if (sid == null) {
            return;
        }
        Tablebeen t = tablebeenDao.queryBuilder().where(TablebeenDao.Properties.TId.eq(sid)).unique();
        if (t != null) {
            t.setStatus(TableStatusConstance.Status_Dining);
            tablebeenDao.update(t);
        }
    }
    private void updateTableRest(String sid){
        Tablebeen t = tablebeenDao.queryBuilder().where(TablebeenDao.Properties.TId.eq(sid)).unique();
        if (t != null) {
            t.setStatus(TableStatusConstance.Status_REST);
            tablebeenDao.update(t);
        }
    }
    private int  getWidth(){
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        return dm.widthPixels;
    }
    private  int getHeight(){
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        return dm.heightPixels;
    }
}